package db

import (
	myDB "db/mysql"
	"fmt"
)

// User : 用户表model
type User struct {
	Username     string
	Email        string
	Phone        string
	SignupAt     string
	LastActiveAt string
	Status       int
}

//用户注册
func UserSignup(username string, password string) bool {
	statement, err := myDB.GetDBConn().Prepare(
		"insert ignore into tbl_user (user_name, user_pwd) value(?, ?)")
	if err != nil {
		fmt.Printf("Falid to insert user, err:%s \n", err.Error())
		return false
	}
	defer statement.Close()
	result, err := statement.Exec(username, password)
	if err != nil {
		fmt.Printf("Falid to insert user exec, err:%s \n", err.Error())
		return false
	}

	if affected, err := result.RowsAffected(); err == nil {
		if affected <= 0 {
			fmt.Printf("File with hash:%s has been uploaded before useranme:%s ", username)
		}
		return true
	}
	return false
}

// 用户登录
func UserSignIn(username, passwd string) bool {
	statement, err := myDB.GetDBConn().Prepare("select * from tbl_user where user_name=? limit 1 ")
	if err != nil {
		fmt.Printf("UserSignIn statement err:%s \n", err.Error())
		return false
	}
	defer statement.Close()
	rows, err := statement.Query(username)
	if err != nil {
		fmt.Printf("UserSignIn query err:%s \n", err.Error())
		return false
	} else if rows == nil {
		fmt.Printf("not found user:%s \n", username)
		return false
	}
	parseRows := myDB.ParseRows(rows)
	if len(parseRows) > 0 && string(parseRows[0]["user_pwd"].([]byte)) == passwd {
		return true
	}
	return false
}

//刷新用户登录token
func UpdateToken(username string, token string) bool {
	statement, err := myDB.GetDBConn().Prepare("replace into tbl_user_token(user_name, user_token) values (?,?)")
	if err != nil {
		fmt.Printf("UpdateToken statement err:%s \n", err.Error())
		return false
	}
	defer statement.Close()
	_, err = statement.Exec(username, token)
	if err != nil {
		fmt.Printf("UpdateToken Exec err:%s \n", err.Error())
		return false
	}
	return true
}

//获取用户信息
func GetUserInfo(username string) (User, error) {
	user := User{}

	statement, err := myDB.GetDBConn().Prepare("select user_name,signup_at from tbl_user where user_name=? limit 1")
	if err != nil {
		fmt.Printf("GetUserInfo statement err:%s \n", err.Error())
		return User{}, err
	}

	defer statement.Close()
	err = statement.QueryRow(username).Scan(&user.Username, &user.SignupAt)

	if err != nil {
		fmt.Printf("GetUserInfo QueryRow err:%s \n", err.Error())
		return User{}, err
	}
	return user, nil
}

//获取用户登录token
func GetUserToken(username string) string {
	stmt, err := myDB.GetDBConn().Prepare(
		"select user_token from tbl_user_token where user_name=? limit 1")
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	defer stmt.Close()

	// 执行查询
	var token string
	err = stmt.QueryRow(username).Scan(&token)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	return token

}
